package com.atguigu.java.ai.langchain4j.store;

import com.atguigu.java.ai.langchain4j.bean.ChatMessages;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

@Component
public class MongoChatMemoryStore implements ChatMemoryStore {


    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<ChatMessage> getMessages(Object messageId) {
        //构建查询条件  根据消息id查询
        Criteria criteria = Criteria.where("messageId").is(messageId);
        Query query = new Query(criteria);
        //调用mongoTemplate查询
        ChatMessages chatMessages = mongoTemplate.findOne(query, ChatMessages.class);
        //查不到  返回空集合
        if(chatMessages == null) return Collections.emptyList();

        //返回数据
        return ChatMessageDeserializer.messagesFromJson(chatMessages.getContent());
    }

    @Override
    public void updateMessages(Object messageId, List<ChatMessage> messages) {

        //构建查询条件  根据消息id查询
        Criteria criteria = Criteria.where("messageId").is(messageId);
        Query query = new Query(criteria);

        //构建修改条件
        Update update = new Update();
        update.set("content", ChatMessageSerializer.messagesToJson(messages));

        //调用mongoTemplate修改
        mongoTemplate.upsert(query,update, ChatMessages.class);

    }

    @Override
    public void deleteMessages(Object messageId) {
        //构建查询条件  根据消息id查询
        Criteria criteria = Criteria.where("messageId").is(messageId);
        Query query = new Query(criteria);
        //调用mongoTemplate删除
        mongoTemplate.remove(query, ChatMessages.class);


    }
}





